package model

import (
	"database/sql/driver"
	"encoding/json"
	"gorm.io/gorm"
	"time"
)

// StringArray 用于存储字符串数组
type StringArray []string

func (a StringArray) Value() (driver.Value, error) {
	return json.Marshal(a)
}

func (a *StringArray) Scan(value interface{}) error {
	if value == nil {
		*a = nil
		return nil
	}
	bytes, ok := value.([]byte)
	if !ok {
		return nil
	}
	return json.Unmarshal(bytes, a)
}

// Consultation 问诊表
type Consultation struct {
	ID                  int64          `gorm:"primaryKey;autoIncrement" json:"id"`
	UserID              int64          `gorm:"index;not null;comment:用户ID" json:"userId"`
	DoctorID            int64          `gorm:"index;not null;comment:医生ID" json:"doctorId"`
	PatientID           int64          `gorm:"index;not null;comment:患者ID" json:"patientId"`
	ConsultationType    int            `gorm:"type:tinyint;not null;comment:问诊类型 1:图文 2:电话 3:视频" json:"consultationType"`
	SymptomDescription  string         `gorm:"type:text;comment:症状描述" json:"symptomDescription"`
	ImageUrls           StringArray    `gorm:"type:json;comment:病例照片" json:"imageUrls"`
	Status              int            `gorm:"type:tinyint;default:1;comment:状态 1:待支付 2:待接诊 3:进行中 4:已完成 5:已取消" json:"status"`
	Fee                 float64        `gorm:"type:decimal(10,2);not null;comment:问诊费用" json:"fee"`
	OrderID             int64          `gorm:"index;comment:订单ID" json:"orderId"`
	CreatedAt           time.Time      `json:"createdAt"`
	UpdatedAt           time.Time      `json:"updatedAt"`
	DeletedAt           gorm.DeletedAt `gorm:"index" json:"-"`
}

func (Consultation) TableName() string {
	return "consultations"
}

// ==================== 模型方法 ====================

// Create 创建问诊
func (c *Consultation) Create(db *gorm.DB) error {
	c.CreatedAt = time.Now()
	c.UpdatedAt = time.Now()
	return db.Create(c).Error
}

// GetByID 根据ID获取问诊详情
func (c *Consultation) GetByID(db *gorm.DB, id, userID int64) error {
	return db.Where("id = ? AND user_id = ?", id, userID).First(c).Error
}

// GetListByUserID 获取用户的问诊列表
func GetConsultationListByUserID(db *gorm.DB, userID int64, status, page, pageSize int) ([]Consultation, int64, error) {
	var consultations []Consultation
	var total int64

	query := db.Model(&Consultation{}).Where("user_id = ?", userID)
	if status > 0 {
		query = query.Where("status = ?", status)
	}

	// 统计总数
	if err := query.Count(&total).Error; err != nil {
		return nil, 0, err
	}

	// 分页查询
	err := query.Scopes(Paginate(page, pageSize)).
		Order("id DESC").
		Find(&consultations).Error

	return consultations, total, err
}

// UpdateStatus 更新问诊状态
func (c *Consultation) UpdateStatus(db *gorm.DB, status int) error {
	return db.Model(c).Updates(map[string]interface{}{
		"status":     status,
		"updated_at": time.Now(),
	}).Error
}

// UpdateDescription 更新症状描述
func (c *Consultation) UpdateDescription(db *gorm.DB, description string, imageUrls []string) error {
	updates := map[string]interface{}{
		"symptom_description": description,
		"updated_at":          time.Now(),
	}
	if len(imageUrls) > 0 {
		updates["image_urls"] = StringArray(imageUrls)
	}
	return db.Model(c).Updates(updates).Error
}

